import os
import sys
import cv2
import pandas as pd
from glob import glob
import shutil

root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(root)

data = os.path.join(root, "datasets")

def draws(input_dir,score_name,scores,outdir):
    scores = pd.read_csv(scores)
    scores = scores[["images", score_name]]
    scores = scores.set_index("images")
    scores = scores.to_dict()
    scores = scores[score_name]
    scores = sorted(scores.items(),key=lambda x:x[1])

    if not os.path.exists(outdir):
        os.makedirs(outdir)
    else:
        shutil.rmtree(outdir)
        os.makedirs(outdir)

    for index,image in enumerate(scores):

        filename = image[0]
        score = image[1]

        image = cv2.imread(os.path.join(input_dir,image[0]))

        cv2.putText(image, '%.2f'%score, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 2)
        cv2.imwrite(os.path.join(outdir,"{}_{}.jpg".format(index,filename)),image)

# draws(os.path.join(root,"datasets","grd_test","fuzzy words"),
#       "JPEQ",
#       os.path.join(root,"outputs/grd_test_JPEQ.csv"),
#       os.path.join(root,"draws","grd_test_JPEQ"))

draws(os.path.join(root,"datasets","tid","distorted_images"),
      "JPEQ2",
      os.path.join(root,"outputs/tid_JPEQ2.csv"),
      os.path.join(root,"draws","tid_JPEQ2"))